package org.geektimes.projects.user.service.impl;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.List;
import java.util.function.Consumer;

/**
 * @FileName: UserServiceImpl
 * @Description: 用户服务实现
 * @Author: MaWenHao
 * @Created: 2021/3/2 - 上午12:26
 */
public class UserServiceImpl implements UserService {

    // private static Logger logger = Logger.getLogger(UserServiceImpl.class.getName());

    /**
     * 通用处理方式
     */
    private static Consumer<Throwable> COMMON_EXCEPTION_HANDLER = e -> System.out.println(e.getCause());

    @Resource(name = "EntityManager")
    private static EntityManager entityManager;

    /**
     * 注册用户
     *
     * @param user 用户对象
     * @return 成功返回<code>true</code>
     */
    @Override
    public boolean register(User user) {
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.persist(user);
        transaction.commit();
        return true;
    }

    /**
     * 注销用户
     *
     * @param user 用户对象
     * @return 成功返回<code>true</code>
     */
    @Override
    public boolean deregister(User user) {
        return false;
    }

    /**
     * 更新用户信息
     *
     * @param user 用户对象
     * @return
     */
    @Override
    public boolean update(User user) {
        return false;
    }

    @Override
    public User queryUserById(Long id) {
        return null;
    }

    @Override
    public User queryUserByNameAndPassword(String name, String password) {
        return null;
    }

    /**
     * 查询所有用户信息
     *
     * @return
     */
    @Override
    public List<User> getALL() {
        String queryAllSql = "SELECT id,name,password,email,phoneNumber FROM users";
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        Query nativeQuery = entityManager.createNativeQuery(queryAllSql, User.class);
        List<User> resultList = nativeQuery.getResultList();
        transaction.commit();
        return resultList;
    }
}
